package com.meiyuetao.myt.es.agent.web.action;

import java.util.Map;

import lab.s2jh.auth.security.AuthUserHolder;
import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.exception.DataAccessDeniedException;
import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.core.security.AclService;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.web.rest.Jackson2LibHandler;
import lab.s2jh.core.web.view.OperationResult;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.rest.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.google.common.collect.Maps;
import com.meiyuetao.myt.core.web.MytBaseController;
import com.meiyuetao.myt.finance.service.AccountSubjectService;
import com.meiyuetao.myt.partner.entity.DistributeDelivery;
import com.meiyuetao.myt.partner.entity.DistributeDelivery.DistributeDeliveryStatusEnum;
import com.meiyuetao.myt.partner.entity.Partner;
import com.meiyuetao.myt.partner.service.DistributeDeliveryService;
import com.meiyuetao.myt.sale.service.ExpressDataTemplateService;
import com.opensymphony.xwork2.interceptor.ParameterNameAware;

@MetaData("分销代理商的销售单管理")
public class DistributeDeliveryController extends MytBaseController<DistributeDelivery, Long> implements ParameterNameAware {

    @Autowired
    private DistributeDeliveryService agentSaleDeliveryService;
    @Autowired
    private ExpressDataTemplateService expressDataTemplateService;
    @Autowired
    private AclService aclService;
    @Autowired
    private AccountSubjectService accountSubjectService;
    @Autowired
    private DistributeDeliveryService distributeDeliveryService;

    @Override
    protected BaseService<DistributeDelivery, Long> getEntityService() {
        return distributeDeliveryService;
    }

    @Override
    @MetaData("查询")
    public HttpHeaders findByPage() {
        // 根据当前功能的业务场景设定过滤敏感信息的JSON序列化输出
        Jackson2LibHandler.setJsonPropertyFilter(SimpleBeanPropertyFilter.serializeAllExcept("totalCostAmount", "commodityCostAmount", "profitRate", "profitAmount"));
        return super.findByPage();
    }

    @Override
    protected void appendFilterProperty(GroupPropertyFilter groupPropertyFilter) {
        // 审核通过的
        groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.NN, "auditDate", true));
        // 没有红冲的
        groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.NU, "redwordDate", true));
        // 当前登录代理商的
        String aclCode = AuthUserHolder.getLogonUser().getAclCode();
        if (StringUtils.isNotBlank(aclCode)) {
            groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.EQ, "agentPartner.code", aclCode));
        }
    }

    @Override
    protected void setupDetachedBindingEntity(Long id) {
        bindingEntity = getEntityService().findDetachedOne(id, "distributeDeliveryDetails");
    }

    @MetaData("行项数据")
    public HttpHeaders details() {
        // 根据当前功能的业务场景设定过滤敏感信息的JSON序列化输出
        Jackson2LibHandler.setJsonPropertyFilter(SimpleBeanPropertyFilter.serializeAllExcept("distributeDelivery", "costPrice", "costAmount", "profitRate", "profitAmount"));
        setModel(buildPageResultFromList(bindingEntity.getDistributeDeliveryDetails()));
        return buildDefaultHttpHeaders();
    }

    @Override
    public HttpHeaders doSave() {
        return super.doSave();
    }

    private static String[] acceptableParameterNames = new String[] { "receivePerson", "mobilePhone", "postCode", "deliveryAddr", "logistics.id", "logisticsNo", "logisticsAmount",
            "deliveryTime", "agentPartner.id", "expressDataTemplate.id", "deliveryType", "title" };

    /**
     * 对于需要给外部用户访问的Controller为了避免用户非法篡改数据 以 @see ParameterNameAware
     * 形式设置自动绑定参数白名单
     */
    @Override
    public boolean acceptableParameterName(String parameterName) {
        return acceptableParameterName(acceptableParameterNames, parameterName);
    }

    @Override
    protected void checkEntityAclPermission(DistributeDelivery entity) {
        // 限定只能访问登录用户所在商家的数据
        String aclCodePrefix = aclService.getLogonUserAclCodePrefix();
        Partner agentPartner = entity.getAgentPartner();
        if (agentPartner != null && StringUtils.isNotBlank(aclCodePrefix)) {
            String agentPartnerCode = agentPartner.getCode();
            if (!agentPartnerCode.startsWith(aclCodePrefix)) {
                throw new DataAccessDeniedException();
            }
        }
    }

    @MetaData("确认收货")
    public HttpHeaders doReceive() {
        Map<String, Object> variables = Maps.newHashMap();
        bindingEntity.setDistributeDeliveryStatus(DistributeDeliveryStatusEnum.S50RECEIVED);
        distributeDeliveryService.bpmUpdate(bindingEntity, this.getRequiredParameter("taskId"), variables);
        setModel(OperationResult.buildSuccessResult("确认收货完成", bindingEntity));
        return buildDefaultHttpHeaders();
    }
}